package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.domain.Book;
import com.example.domain.Category;
import com.example.domain.Bookshelf;
import com.example.domain.Room;
import com.example.domain.Library;
import com.example.dto.BookAddDTO;
import com.example.dto.BookUpdateDTO;
import com.example.exception.BusinessException;
import com.example.service.BookService;
import com.example.service.OperationLogService;
import com.example.mapper.BookMapper;
import com.example.mapper.CategoryMapper;
import com.example.mapper.BorrowRecordMapper;
import com.example.mapper.BookshelfMapper;
import com.example.mapper.RoomMapper;
import com.example.mapper.LibraryMapper;
import com.example.util.Result;
import com.example.vo.BookWithLocationVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
* @author HP
* @description 针对表【book】的数据库操作Service实现
* @createDate 2025-08-18 19:31:05
*/
@Service
public class BookServiceImpl extends ServiceImpl<BookMapper, Book>
    implements BookService{

    @Autowired
    private BookMapper bookMapper;
    
    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private OperationLogService operationLogService;
    
    @Autowired
    private BorrowRecordMapper borrowRecordMapper;
    
    @Autowired
    private BookshelfMapper bookshelfMapper;
    
    @Autowired
    private RoomMapper roomMapper;
    
    @Autowired
    private LibraryMapper libraryMapper;

    @Override
    public boolean existsById(Long id) {
        return bookMapper.selectById(id) != null;
    }

    @Override
    public Result addBook(BookAddDTO bookAddDTO) {
        try {
            Book book = new Book();
            BeanUtils.copyProperties(bookAddDTO, book);
            
            // 验证图书信息
            validateBook(book);
            
            boolean result = save(book);
            if (result) {
                return Result.success(book);
            } else {
                return Result.error("添加图书失败");
            }
        } catch (BusinessException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            return Result.error("添加图书失败：" + e.getMessage());
        }
    }

    @Override
    public Result updateBook(BookUpdateDTO bookUpdateDTO) {
        try {
            if (bookUpdateDTO.getId() == null) {
                return Result.error("图书ID不能为空");
            }
            
            Book existingBook = getById(bookUpdateDTO.getId());
            if (existingBook == null) {
                return Result.error("图书不存在");
            }
            
            Book book = new Book();
            BeanUtils.copyProperties(bookUpdateDTO, book);
            
            // 验证图书信息
            validateBook(book);
            
            boolean result = updateById(book);
            if (result) {
                return Result.success("更新图书成功");
            } else {
                return Result.error("更新图书失败");
            }
        } catch (BusinessException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            return Result.error("更新图书失败：" + e.getMessage());
        }
    }

    @Override
    public Result removeBook(Long id) {
        try {
            if (id == null) {
                return Result.error("图书ID不能为空");
            }
            
            Book book = getById(id);
            if (book == null) {
                return Result.error("图书不存在");
            }
            
            // 检查是否有未归还的副本
            if (hasUnreturnedCopies(id)) {
                return Result.error("该图书有未归还的副本，无法删除");
            }
            
            boolean result = removeById(id);
            if (result) {
                return Result.success("删除图书成功");
            } else {
                return Result.error("删除图书失败");
            }
        } catch (Exception e) {
            return Result.error("删除图书失败：" + e.getMessage());
        }
    }

    @Override
    public List<Book> queryBooks(Book book) {
        QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
        
        if (book.getTitle() != null && !book.getTitle().trim().isEmpty()) {
            queryWrapper.like("title", book.getTitle().trim());
        }
        if (book.getAuthor() != null && !book.getAuthor().trim().isEmpty()) {
            queryWrapper.like("author", book.getAuthor().trim());
        }
        if (book.getPublisher() != null && !book.getPublisher().trim().isEmpty()) {
            queryWrapper.like("publisher", book.getPublisher().trim());
        }
        if (book.getCategoryId() != null) {
            queryWrapper.eq("category_id", book.getCategoryId());
        }
        if (book.getBookshelfId() != null) {
            queryWrapper.eq("bookshelf_id", book.getBookshelfId());
        }
        if (book.getBookStatus() != null) {
            queryWrapper.eq("book_status", book.getBookStatus());
        }
        
        return bookMapper.selectList(queryWrapper);
    }

    @Override
    public List<Book> getBooksByCategoryId(Long categoryId) {
        if (categoryId == null) {
            return List.of();
        }
        QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category_id", categoryId);
        return bookMapper.selectList(queryWrapper);
    }

    @Override
    public List<Category> getAllCategories() {
        return categoryMapper.selectList(null);
    }

    @Override
    public BookWithLocationVO getBookWithLocationById(Long id) {
        if (id == null || id <= 0) {
            return null;
        }
        
        // 获取图书基本信息
        Book book = bookMapper.selectById(id);
        if (book == null) {
            return null;
        }
        
        // 创建带位置信息的VO
        BookWithLocationVO bookWithLocation = new BookWithLocationVO();
        BeanUtils.copyProperties(book, bookWithLocation);
        
        // 获取位置信息
        if (book.getBookshelfId() != null) {
            // 获取书架信息
            Bookshelf bookshelf = bookshelfMapper.selectById(book.getBookshelfId());
            if (bookshelf != null) {
                bookWithLocation.setBookshelfNumber(bookshelf.getNumber());
                
                // 获取房间信息
                if (bookshelf.getRoomId() != null) {
                    Room room = roomMapper.selectById(bookshelf.getRoomId());
                    if (room != null) {
                        bookWithLocation.setRoomName(room.getName());
                        
                        // 获取图书馆信息
                        if (room.getLibraryId() != null) {
                            Library library = libraryMapper.selectById(room.getLibraryId());
                            if (library != null) {
                                bookWithLocation.setLibraryName(library.getName());
                            }
                        }
                    }
                }
            }
        }
        
        // 设置完整位置路径
        bookWithLocation.setFullLocationPath();
        
        return bookWithLocation;
    }
    
    @Override
    public List<BookWithLocationVO> queryBooksWithLocation(Book queryBook) {
        // 先查询符合条件的图书
        List<Book> books = queryBooks(queryBook);
        
        // 转换为带位置信息的VO列表
        return books.stream().map(book -> {
            BookWithLocationVO bookWithLocation = new BookWithLocationVO();
            BeanUtils.copyProperties(book, bookWithLocation);
            
            // 获取位置信息
            if (book.getBookshelfId() != null) {
                // 获取书架信息
                Bookshelf bookshelf = bookshelfMapper.selectById(book.getBookshelfId());
                if (bookshelf != null) {
                    bookWithLocation.setBookshelfNumber(bookshelf.getNumber());
                    
                    // 获取房间信息
                    if (bookshelf.getRoomId() != null) {
                        Room room = roomMapper.selectById(bookshelf.getRoomId());
                        if (room != null) {
                            bookWithLocation.setRoomName(room.getName());
                            
                            // 获取图书馆信息
                            if (room.getLibraryId() != null) {
                                Library library = libraryMapper.selectById(room.getLibraryId());
                                if (library != null) {
                                    bookWithLocation.setLibraryName(library.getName());
                                }
                            }
                        }
                    }
                }
            }
            
            // 设置完整位置路径
            bookWithLocation.setFullLocationPath();
            
            return bookWithLocation;
        }).toList();
    }

    /**
     * 验证分类是否存在
     */
    public boolean existsCategory(Long categoryId) {
        if (categoryId == null) {
            return false;
        }
        return categoryMapper.selectById(categoryId) != null;
    }

    /**
     * 验证图书信息
     */
    private void validateBook(Book book) {
        // 检查分类是否存在
        if (!existsCategory(book.getCategoryId())) {
            throw new BusinessException(400, "图书分类不存在");
        }
    }
    
    /**
     * 检查图书是否有未归还的副本
     */
    private boolean hasUnreturnedCopies(Long bookId) {
        // 这里应该检查借阅记录，暂时返回false
        return false;
    }
}